package cn.gaily.eduservice.controller;


import cn.gaily.commonutils.R;
import cn.gaily.eduservice.entity.EduVideo;
import cn.gaily.eduservice.entity.vo.VideoVo;
import cn.gaily.eduservice.feignclient.VodClient;
import cn.gaily.eduservice.service.EduVideoService;
import cn.gaily.servicebase.exceptionhandler.GuliException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author xuchengwei
 * @since 2021-07-05
 */
@Api(description = "小节接口")
@RestController
@RequestMapping("/eduservice/video")
@CrossOrigin
public class EduVideoController {
    @Autowired
    EduVideoService eduVideoService;
    @Autowired
    VodClient vodClient;

    @ApiOperation("根据小节id查询")
    @GetMapping("/getVideoInfo/{id}")
    public R getVideoInfo(@PathVariable String id){
        EduVideo video = eduVideoService.getById(id);
        return R.ok().data("video", video);
    }

    @ApiOperation(value = "添加小节")
    @PostMapping("/addVideo")
    public R addVideo(@RequestBody EduVideo eduVideo){
        eduVideoService.save(eduVideo);
        return R.ok();
    }

    @ApiOperation("修改小节")
    @PostMapping("/updateVideo")
    public R updateVideo(@RequestBody EduVideo eduVideo){
        boolean update = eduVideoService.updateById(eduVideo);
        return update ? R.ok() : R.error();
    }

    @ApiOperation("删除小节")
    @DeleteMapping("/deleteVideo/{videoId}")
    public R deleteVideo(@PathVariable String videoId){
        EduVideo video = eduVideoService.getById(videoId);
        String videoSourceId = video.getVideoSourceId();
        //先删视频，后删小节
        if(!StringUtils.isEmpty(videoSourceId) ) {
            R r = vodClient.removeAliyVideo(videoSourceId);
            if(r.getCode() == 20001){
                throw new GuliException(20001,"删除失败，熔断器触发");
            }
        }
        boolean remove = eduVideoService.removeById(videoId);

        return remove ? R.ok() : R.error();
    }

}

